/*
 *
 *   业务：业务处理系统
 *   作者：宫旭童
 *
 * */
//信访状态
//1.已提交 信访事项已被相关部门或单位接收，生成了信访编号，等待进一步处理。
//2.待审核 信访事项正在进行初步审查，以确定其合理性和可处理性。
//3.已审核 信访事项已通过初步审查，正在等待分流到相关部门或单位进行详细调查和处理。
//4.待处理 信访事项正在由相关部门或单位进行调查处理，收集相关证据和信息。
//5.已处理 信访事项已经被处理。


package org.example.petitionplatformsystem.controller;

import org.example.petitionplatformsystem.Response;
import org.example.petitionplatformsystem.converter.PetitionAuditConverter;
import org.example.petitionplatformsystem.dao.model.*;
import org.example.petitionplatformsystem.dto.PetitionDTO.PetitionsAuditDTO;
import org.example.petitionplatformsystem.service.*;
import org.example.petitionplatformsystem.utils.EventTransferUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/petitions")
@RestController
public class TransactionController {
    @Autowired


    //信访状态表服务
    private final ComplaintStatusService CSService;
    //信访结果表服务
    private final ProcessResultsService PRService;
    //信访事件表服务
    private final PetitionEventsService PEService;
    //申请延期表服务
    private final DelayRequestsService DRService;
    //审批表服务
    private final ApprovalsService approvalsService;
    //职员表服务
    private final EmployeesService employeesService;

    public TransactionController(ComplaintStatusService CSService,
                                 ProcessResultsService PRService,
                                 PetitionEventsService PEService,
                                 DelayRequestsService DRService,
                                 ApprovalsService approvalsService,
                                 EmployeesService employeesService){
        this.CSService = CSService;
        this.PEService = PEService;
        this.PRService = PRService;
        this.DRService = DRService;
        this.approvalsService = approvalsService;
        this.employeesService = employeesService;
    }


    //信访事件审核并分发
    @PostMapping("add")
    public Response<Void> petitionsAudit(@RequestBody PetitionsAuditDTO petitionsAuditDTO)   {
//        try{
            //审核

            approvalsService.addApproval(PetitionAuditConverter.PAC(petitionsAuditDTO));
            System.out.println("状态  "+petitionsAuditDTO.getStatus());
            //分发
            if(petitionsAuditDTO.getStatus() >= 3){
                System.out.println("状态2  "+petitionsAuditDTO.getStatus());
                List<Employees> employeesList = employeesService.getAllEmployees();
                PetitionEvents petitionEvents = PEService.getPetitionEventById(petitionsAuditDTO.getEventId());

                PEService.updatePetitionEvent(EventTransferUtil.ETU(petitionEvents, employeesList));//具体地分发逻辑

                System.out.println(employeesList.get(0).getWork_Num());
                System.out.println(employeesList.get(1).getWork_Num());
                System.out.println(employeesList.get(2).getWork_Num());
            }

            return Response.newSuccessResponse(null);
//        }
//        catch (Exception e){
//            return Response.newFailResponse("审批失败！请检查参数");
//        }

    }

    //直接回复信访事件：告诉用户该事件已经被提交。
    @PostMapping("reply")
    public Response<Void> reply(@RequestParam Long petitionId,@RequestParam String replyContent){
        int status = 1;//状态：已提交

        ComplaintStatus complaintStatus = new ComplaintStatus();
        complaintStatus.setEventID(petitionId);
        complaintStatus.setStatus(status);
        complaintStatus.setReplyContent(replyContent);
        complaintStatus.setUpdateTime(String.valueOf(LocalDateTime.now()));

        try{
            CSService.updateComplaintStatus(complaintStatus);
            return Response.newSuccessResponse(null);
        }
        catch (Exception e){
            return Response.newFailResponse("更新信访状态表失败，请检查信访号");
        }
    }

    //信访事件完成
    @PostMapping("approve")
    public Response<Void> approve(@RequestParam Long petitionId, @RequestParam String resultDetails){
        int status = 5;//状态：已处理。
        Long userId = PEService.getPetitionEventById(petitionId).getUserID();

        ComplaintStatus complaintStatus = new ComplaintStatus();
        complaintStatus.setEventID(petitionId);
        complaintStatus.setStatus(status);
        complaintStatus.setUpdateTime(String.valueOf(LocalDateTime.now()));

        ProcessResults processResults = new ProcessResults();
        processResults.setResultDetails(resultDetails);
        processResults.setVisitID(petitionId);
        processResults.setCreatedAt(LocalDateTime.now());
        processResults.setUserID(userId);

        try{
            CSService.updateComplaintStatus(complaintStatus);
            PRService.addProcessResult(processResults);
            return Response.newSuccessResponse(null);
        }
        catch (Exception e){
            return Response.newFailResponse("更新表失败，请检查信访号");
        }
    }

    //申请延期处理事件
    @PostMapping("extension")
    public Response<Void> extension(@RequestBody DelayRequests delayRequests){
        try{
            DRService.addDelayRequest(delayRequests);
            return Response.newSuccessResponse(null);
        }
        catch (Exception e){
            return Response.newFailResponse("更新表失败，请检查信访号");
        }
    }

    //转送信访事件
    @PostMapping("transfer")
    public Response<Void> transfer(@RequestParam Long petitionId, @RequestParam Long workId){
        PetitionEvents petitionEvents = PEService.getPetitionEventById(petitionId);
        petitionEvents.setWorkId(workId);
        try{
            PEService.updatePetitionEvent(petitionEvents);
            return Response.newSuccessResponse(null);
        }
        catch (Exception e){
            return Response.newFailResponse("更新表失败，请检查信访号");
        }
    }

    //审核：获取所有待审核记录（即用户新提交的信访记录）
    @GetMapping("getNotApproved")
    public Response<List<PetitionEvents>> getNotApproved(){
        try{
            return Response.newSuccessResponse(PEService.getNotApproved());
        }catch (Exception e){
            return Response.newFailResponse("请求失败");
        }
    }

    //处理：获取所有审核通过的记录
    @GetMapping("getApproved")
    public Response<List<Approvals>> getApproved(){
        try{
            return Response.newSuccessResponse(approvalsService.getApproved());
        }catch (Exception e){
            return Response.newFailResponse("请求失败");
        }
    }

    //获取当前业务员待处理的所有记录
    @GetMapping("getEventByWorkId/{workId}")
    public Response<List<PetitionEvents>> getEventByWorkId(@PathVariable Long workId){
        try{
            return Response.newSuccessResponse(PEService.getEventByWorkId(workId));
        }catch (Exception e){
            return Response.newFailResponse("请求失败");
        }
    }
    @PostMapping("/refuse/{eventId}")
     public Response<Void> refuse(@PathVariable Long eventId){
         try{
             PetitionEvents petitionEvent = PEService.getPetitionEventById(eventId);
             Approvals approvals = new Approvals();
             approvals.setEventID(eventId);
             approvals.setApprovalStatus("拒绝");
             approvals.setApprovalNotes("不符合流程");
             approvals.setUserID(petitionEvent.getUserID());
             LocalDateTime now = LocalDateTime.now();
               approvals.setApprovalDate(now);
             approvalsService.addApproval(approvals);
             petitionEvent.setStatus(-1L);
             PEService.updatePetitionEvent(petitionEvent);
             return Response.newSuccessResponse(null);
         }catch (Exception e){
             return Response.newFailResponse("请求失败");
         }
    }
    @GetMapping("/getAllAprovals/{status}")
     public Response<List<PetitionEvents>> getAllAprovals(@PathVariable String status){

            Long statusNumber = Long.valueOf(status);
            return Response.newSuccessResponse(PEService.getEventByStatus(statusNumber));

    }





}
